import 'package:e_reception_flutter/colors/colors.dart';
import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/ui/app_main.dart';
import 'package:e_reception_flutter/ui/new_terminal/binding_terminal/bind_terminal_info_confirm_page.dart';
import 'package:e_reception_flutter/ui/new_terminal/binding_terminal/binding_terminal_page.dart';
import 'package:e_reception_flutter/ui/new_terminal/binding_terminal/terminal_basic_info_page.dart';
import 'package:e_reception_flutter/ui/new_terminal/binding_terminal/terminal_detail_info_page.dart';
import 'package:e_reception_flutter/ui/new_terminal/new_terminal_list/bean/new_terminal_response_bean.dart';
import 'package:e_reception_flutter/ui/new_terminal/new_terminal_list/bean/set_terminal_state_type.dart';
import 'package:e_reception_flutter/ui/new_terminal/new_terminal_list/widgets/terminal_state_menu_dialog.dart';
import 'package:e_reception_flutter/utils/vg_global_func.dart';
import 'package:e_reception_flutter/utils/vg_toast_utils.dart';
import 'package:e_reception_flutter/vg_widgets/vg_image_widget/vg_cache_net_work_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:vg_base/vg_string_util_lib.dart';

import '../new_terminal_list_page.dart';

/// 新终端列表
///
/// @author: zengxiangxi
/// @createTime: 1/15/21 4:01 PM
/// @specialDemand:
class NewTerminalListWidget extends StatelessWidget {

  final List<NewTerminalListItemBean> list;

  final VoidCallback onMultRefresh;

  const NewTerminalListWidget(
      this.list, {
        Key key,
        this.onMultRefresh,
      }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return _toListWidget();
  }

  Widget _toListWidget() {
    return ListView.separated(
        itemCount: list?.length ?? 0,
        shrinkWrap: true,
        padding: const EdgeInsets.all(0),
        physics: BouncingScrollPhysics(),
        keyboardDismissBehavior: ScrollViewKeyboardDismissBehavior.onDrag,
        itemBuilder: (BuildContext context, int index) {
          return _toListItemWidget(context, index, list?.elementAt(index));
        },
        separatorBuilder: (BuildContext context, int index) {
          return SizedBox(height: 0);
        });
  }

  ///列表项
  Widget _toListItemWidget(
      BuildContext context, int index, NewTerminalListItemBean itemBean) {
    return GestureDetector(
      behavior: HitTestBehavior.translucent,
      onTap: () async {
        if (StringUtils.isEmpty(itemBean?.hsn)) {
          VgToastUtils.toast(AppMain.context, "终端获取异常");
          return;
        }
        dynamic result;
        if(itemBean?.bindflg == "00"){
          result = await BindTerminalInfoConfirmPage.navigatorPush(context, itemBean?.hsn);
        }else{
          result = await TerminalDetailInfoPage.navigatorPush(context, itemBean?.hsn, router: NewTerminalListPage.ROUTER);
        }

        if (result is bool && result && onMultRefresh != null) {
          onMultRefresh();
        }
      },
      child: Container(
        height: 87,
        child: Row(
          children: <Widget>[
            SizedBox(
              width: 15,
            ),
            ClipRRect(
                borderRadius: BorderRadius.circular(4),
                child: Container(
                  width: 60,
                  height: 60,
                  child: VgCacheNetWorkImage(
                    itemBean?.terminalPicurl ?? "",
                    defaultErrorType: ImageErrorType.head,
                    errorWidget:Container(
                      color: Color(0xff3a3f50),
                      child: Center(
                        child:  Text(
                          "暂无\n图片",
                          maxLines: 2,
                          overflow: TextOverflow.ellipsis,
                          style: TextStyle(
                              color: VgColors.INPUT_BG_COLOR,
                              fontSize: 14,
                              height: 1.5
                          ),
                        ),
                      ),
                    ),
                  ),
                )),
            Expanded(child: _toContentWidget(context, index, itemBean)),
            _toButtonStatusWidget(itemBean),
          ],
        ),
      ),
    );
  }

  Widget _toContentWidget(context, int index, NewTerminalListItemBean itemBean) {
    SetTerminalStateType currentType = itemBean.getTerminalState();
    return Container(
      margin: const EdgeInsets.only(left: 12),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Row(
            children: <Widget>[
              Text(
                StringUtils.isNotEmpty(itemBean?.terminalName)
                    ? (itemBean?.terminalName ?? "")
                    : "终端显示屏${(index ?? 0) + 1}",
                maxLines: 1,
                overflow: TextOverflow.ellipsis,
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 15,
                  // fontWeight: FontWeight.w600
                ),
              ),
              Spacer(),
              GestureDetector(
                onTapUp: (detail){
                  if((itemBean?.onOff??0) == 0){
                    return;
                  }
                  TerminalStateMenuDialogUtils.showMenuDialog(
                      context: context,
                  tabUpDetails: detail,
                  itemMap: _getMenuMap(context, itemBean),
                    sortType: currentType
                  );
                },
                child: Visibility(
                  visible: (itemBean?.bindflg??"") == "01",
                  child: Container(
                    alignment: Alignment.centerRight,
                    width: 60,
                    child: Row(
                      children: [
                        Container(
                          alignment: Alignment.centerRight,
                          width: 48,
                          child: Text(
                              (itemBean.onOff == null || itemBean.onOff !=1 || itemBean.getTerminalIsOff())?"已关机":"正常开机",
                            style: TextStyle(
                              fontSize: 12,
                              color: (itemBean.onOff == null || itemBean.onOff !=1 || itemBean.getTerminalIsOff())
                                  ?ThemeRepository.getInstance().getDefaultGrayColor_FF5E687C()
                                  :ThemeRepository.getInstance().getHintGreenColor_00C6C4(),
                            ),
                          ),
                        ),
                        SizedBox(width: 5,),
                        Visibility(
                            visible: (itemBean?.onOff??0) != 0,
                            child: Image(
                              image: AssetImage("images/icon_shape_arrow_down.png"),
                              width: 7,
                            ),
                        ),
                      ],
                    ),
                  ),
                ),
              ),
            ],
          ),
          SizedBox(
            height: 4,
          ),
          Container(
            margin: const EdgeInsets.only(right: 12),
            child: Text(
              showOriginEmptyStr(itemBean?.position) ?? itemBean?.address ?? "",
              maxLines: 1,
              overflow: TextOverflow.ellipsis,
              style: TextStyle(
                color: VgColors.INPUT_BG_COLOR,
                fontSize: 12,
              ),
            ),
          ),
          SizedBox(
            height: 4,
          ),
          Text(
            "管理员：${itemBean?.manager ?? "-"}${_getLoginStr(itemBean?.loginName) ?? ""}",
            maxLines: 1,
            overflow: TextOverflow.ellipsis,
            style: TextStyle(
              color: VgColors.INPUT_BG_COLOR,
              fontSize: 12,
            ),
          )
        ],
      ),
    );
  }

  void _onOpen(NewTerminalListItemBean itemBean){
    print("开机");
  }

  void _screenOff(NewTerminalListItemBean itemBean){
    print("息屏开机");
  }

  void _off(NewTerminalListItemBean itemBean){
    print("关机");
  }

  Map<SetTerminalStateType,ValueChanged> _getMenuMap(BuildContext context, NewTerminalListItemBean itemBean){
    //开机状态，
    if(itemBean.onOff == 1 || itemBean.onOff == 2){
      return {
        SetTerminalStateType.open:(_){
          _onOpen?.call(itemBean);
        },
        // SetTerminalStateType.screenOff:(_){
        //   _screenOff?.call(itemBean);
        // },
        SetTerminalStateType.off:(_){
          _off?.call(itemBean);
        },
        SetTerminalStateType.autoOnOff:(_){
          _off?.call(itemBean);
        },
      };
    }

  }

  String _getLoginStr(String loginName) {
    if (loginName == null || loginName == "") {
      return null;
    }
    return "（$loginName账号登录）";
  }

  Widget _toButtonStatusWidget(NewTerminalListItemBean itemBean) {
    if (!(itemBean?.bindflg == "00")) {
      return SizedBox(
        width: 15,
      );
    }
    return Offstage(
      offstage: !(itemBean?.bindflg == "00"),
      child: Container(
        width: 90,
        child: _toBindButtonWidget(itemBean),
      ),
    );
  }

  Widget _toBindButtonWidget(NewTerminalListItemBean itemBean) {
    return Align(
      alignment: Alignment.topCenter,
      child: Builder(
        builder: (BuildContext context) => Container(
          width: 60,
          height: 28,
          margin: const EdgeInsets.symmetric(vertical: 12),
          decoration: BoxDecoration(
              color: ThemeRepository.getInstance().getMinorRedColor_F95355(),
              borderRadius: BorderRadius.circular(14)),
          child: Center(
            child: Text(
              "绑定",
              maxLines: 1,
              overflow: TextOverflow.ellipsis,
              style: TextStyle(color: Colors.white, fontSize: 13, height: 1.2),
            ),
          ),
        ),
      ),
    );
  }
}
